import React from "react";
import { BasicInfo } from "../operation/basic_info";
import { BasicInfoItem } from "../operation/table_data_model";
import { doMakeSecrets } from '../operation/make_secrets';
import AddItem from "./addItem";
import _ from 'lodash'

const DESC_MAP = {
    userName: "用户",
    password: "密码",
    desc: "简述",
    site: "网站",
    email: "邮箱",
    phone: "手机",
    remark: "备注",
}
const DISPLAY_LIST = ['userName', 'password', 'email', 'phone', 'site', 'remark']
export default class DataDisplay extends React.PureComponent<any, any, any> {
    // all data.
    initialData: any[];
    // 筛选条件
    filterCondition: string;
    constructor(props) {
        super(props);
        this.state = {
            // for display.
            allData: [],
            currentPage: 'list', // list | add
        }
        this.initialData = []
    }
    componentDidMount() {
        this.getAll();
    }
    switchPage = (e) => {
        this.setState({currentPage: e.target.getAttribute("data-name")})
    }
    getAll = () => {
        BasicInfo.getAllData().then(all => {
            try {
                let decryptedData = all.map(data => {
                    data.body = JSON.parse(doMakeSecrets().decrypt(data.body))
                    return data;
                })
                this.initialData = decryptedData;
                this.setState({allData: decryptedData})
            } catch (e) {
                console.error(e);
                alert("Descrypt Data Error!")
            }
        }).catch(e => {
            console.error("fetch data err:", e)
        }).finally(() => {
            console.log(this.state.allData)
        })
    }
    getPassword = (e) => {
        let target = e.target
        console.log(target.id)
    }
    switchPageFromChild = (page) => {
        if (['list', 'add'].indexOf(page) === -1) {
            console.error("数据非法" + page)
            return;
        }
        this.setState({currentPage: page})
    }
    updateInfo = (e) => {
        let target = e.target;
        console.log(target)
        let info = target.getAttribute("data-saved")
        console.log(info)
        let dealedInfo = info.split("-")
        if (dealedInfo.length !== 2) {
            throw Error("data-saved info err")
        }
        let willUpdateInfo = this.state.allData[dealedInfo[1]]
        if (willUpdateInfo.id != dealedInfo[0]) {
            throw Error("data not match!")
        }
        window.sessionStorage.setItem("$codebook-updateobj", JSON.stringify({id: willUpdateInfo.id, ...willUpdateInfo.body}))

        this.switchPageFromChild("add")
    }
    copyToClipboard = (e) => {
        try {
            console.log('begin write to clipboard')
            let content = e.target.getAttribute("data-content");
            if (navigator.clipboard) {
                navigator.clipboard.writeText(content)
            } else {
                console.warn("CURRENT ENV NOT SUPPORT nav.clipboard")
                var oInput = document.createElement('input');
                oInput.value = content;
                // oInput.style.display = 'none';
                document.body.appendChild(oInput);
                oInput.select(); // 选择对象
                oInput.setSelectionRange(0, oInput.value.length), document.execCommand('Copy');
                document.body.removeChild(oInput);
            }
        } catch (e) {
            console.error(e)
            alert(`copy err:` + e.message)
        }
    }
    genListItem = (data, key) => {
        if (_.isEmpty(data[key])) {
            return null;
        }
        let desc = DESC_MAP[key]
        switch(key) {
            case 'site':
                return <li className="list-group-item" key={key}>
                    {desc}: <a href={data[key]} className="btn btn-link"><i className="fas fa-link"></i>{data[key]}</a>
                </li>
            case 'password':
                return <li className="list-group-item" key={key}>
                    {desc}: <code className="ms-2">{data[key]}</code>
                    <button className="btn btn-link" data-content={data[key]} onClick={this.copyToClipboard}>
                        <i className="fas fa-clipboard" data-content={data[key]}></i>
                    </button>
                </li>
            default:
                return <li className="list-group-item" key={key}>
                    {desc}：{data[key]}
                </li>
        }
    }
    setFilter = () => {
        let condition = window.prompt("请输入过滤条件", "")
        if (this.initialData && this.initialData.length && !_.isEmpty(condition)) {
            let filterResult = this.initialData.map((item) => {
                let content: BasicInfoItem = item.body;
                for (let key of DISPLAY_LIST) {
                    if (content[key] && content[key].indexOf(condition) !== -1) {
                        return item;
                    }
                }
            })
            filterResult = _.compact(filterResult)
            console.log('filterResult:', filterResult)
            this.setState({allData: filterResult})
        } else {
            if (this.state.allData !== this.initialData) {
                this.setState({allData: this.initialData})
            }
        }
    }
    listAll = () => {
        const CommonHeader = <div className="d-flex justify-content-end mt-3">
            <button className="btn btn-primary btn-sm" onClick={this.setFilter}>
                <i className="fas fa-filter"></i> 关键字筛选
            </button>
            <button className="btn btn-primary btn-sm ms-3" onClick={this.getAll}>
                <i className="fas fa-cloud-download-alt"></i> 获取数据
            </button></div>
        if (this.state.allData && this.state.allData.length) {
            let lists = this.state.allData.map((data, index) => {
                let dataObj:BasicInfoItem = data.body;
                return <div key={data.id} className="accordion-item">
                    <div className="accordion-header" id={'heading'+data.id}>
                        <button className="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target={`#collapse${data.id}`} 
                            aria-expanded="true" aria-controls="collapseOne">
                            {dataObj.desc}
                        </button>
                    </div>
                    <div className="accordion-collapse collapse" id={`collapse${data.id}`} data-bs-parent="#alldatalist">
                        <div className="accordion-body">
                        <ul className="list-group list-group-flush">
                            {DISPLAY_LIST.map(key => this.genListItem(dataObj, key))}
                            <li className="list-group-item">
                                <div className="d-flex justify-content-end">
                                    <button data-saved={data.id+"-"+index} className="btn btn-outline-secondary btn-sm" onClick={this.updateInfo}>
                                        <i className="fas fa-edit" data-saved={data.id+"-"+index} ></i>
                                        更新
                                    </button>
                                </div>
                            </li>
                        </ul>
                            
                        </div>
                    </div>
                    
                </div>
            })
            return <div>
                <div className="accordion" id="alldatalist">{lists}</div>
                {CommonHeader}
            </div>
        } else {
            return (
            <div>
                <div className="text-center p-5 text-secondary">空数据&nbsp;&nbsp;<i className="fas fa-box-open text-primary"></i></div>
                {CommonHeader}
            </div>)
        }
    }
    render() {
        let displayClass = this.state.currentPage === 'list' ? 'nav-link active' : 'nav-link'
        let addClass = this.state.currentPage === 'add' ? 'nav-link active' : 'nav-link'
        return(
            <div>
                <ul className="nav nav-tabs nav-fill">
                    <li className="nav-item">
                        <a className={displayClass} aria-current="page" href="#" onClick={this.switchPage} data-name='list'>展示信息</a>
                    </li>
                    <li className="nav-item">
                        <a className={addClass} aria-current="page" href="#" onClick={this.switchPage} data-name='add'>信息处理</a>
                    </li>
                </ul>
                <div>
                    {
                        this.state.currentPage === 'list' && this.listAll()
                    }
                    {
                        this.state.currentPage === 'add' && <AddItem switch={this.switchPageFromChild}/>
                    }
                </div>
            </div>
        )
    }
}